package cn.szsys.integration.helper.business.impl;

import cn.szsys.integration.dto.EconomicCapabilityDTO;
import cn.szsys.integration.ex.BusinessException;
import cn.szsys.integration.ex.enums.ExceptionEnum;
import cn.szsys.integration.helper.BusinessBeanNameConstant;
import cn.szsys.integration.helper.business.AbstractEconomicCapabilityHandlerChain;
import cn.szsys.integration.util.EncryptUtil;
import cn.szsys.integration.util.OkHttpUtil;
import cn.szsys.integration.util.R;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.Serializable;
import java.util.UUID;

/**
 * 康寿连枝
 *
 * @author Ryan
 * @since 2025-06-19
 **/
@Component(BusinessBeanNameConstant.EconomicCapability.KSLZ_ECONOMIC_CAPABILITY_HANDLER_CHAIN)
@Slf4j
public class KslzEconomicCapabilityHandlerChain extends AbstractEconomicCapabilityHandlerChain {

    @Value("${economic-capability.hlks.url}")
    private String url;
    @Value("${economic-capability.hlks.mer-no}")
    private String merNo;
    @Value("${economic-capability.hlks.aes-key}")
    private String aesKey;
    @Value("${economic-capability.hlks.aes-iv}")
    private String iv;
    @Value("${economic-capability.hlks.job-id}")
    private String jobId;

    public SecretKeySpec keySpec;
    public IvParameterSpec ivParameterSpec;

    @PostConstruct
    public void init() {
        keySpec = new SecretKeySpec(aesKey.getBytes(), "AES");
        ivParameterSpec = new IvParameterSpec(iv.getBytes());
    }

    /**
     * 转换对应结果并设置计费信息
     *
     * @param obj           obj
     * @param consumingTime consumingTime
     * @return {@link R}
     * @author Ryan
     */
    @Override
    public R<?> convertResultAndBilling(JSONObject obj, long consumingTime) {
        KslzResDTO res = JSON.parseObject(obj.toString(), KslzResDTO.class);
        if (res.isSuccess()) {
            try {
                String decrypt = EncryptUtil.CBC.decrypt(res.getData(), keySpec, ivParameterSpec);
                log.info("请求KLSZ经济能力[响应], 解密数据:{}", decrypt);
                return R.success(JSON.parseObject(decrypt));
            } catch (Exception e) {
                throw new BusinessException(ExceptionEnum.OP_FAIL, "请求出错!");
            }
        }
        throw new BusinessException(ExceptionEnum.OP_FAIL, "请求出错!");
    }

    /**
     * 执行业务处理
     *
     * @param dto          参数
     * @param reqStartTime reqStartTime
     * @return {@link R}
     * @author Ryan
     */
    @Override
    public R<?> doHandle(EconomicCapabilityDTO dto, long reqStartTime) {
        String orderNo = "KL".concat(String.valueOf(reqStartTime));
        String body = "{\n" +
                "    \"job_id\": \"" + jobId + "\",\n" +
                "    \"merchant_order_no\": \"" + orderNo + "\",\n" +
                "    \"cert_no\": \"" + dto.getIdCard() + "\"\n" +
                "}";

        String encrypt;
        try {
            encrypt = EncryptUtil.CBC.encrypt(body, keySpec, ivParameterSpec);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String bodyRaw = "{\n" +
                "\"head\": {" +
                "\"merchant_no\":\"" + merNo + "\",\n" +
                "\"uuid\":\"" + UUID.randomUUID() + "\",\n" +
                "\"service\":\"10001\"\n" +
                "},\n" +
                "\"data\": \"" + encrypt + "\"" +
                "}";

        log.info("请求KLSZ经济能力[请求], body :{}", bodyRaw);
        long startTime = System.currentTimeMillis();
        OkHttpUtil.OkhttpResponse response = OkHttpUtil.builder()
                .url(url)
                .post(bodyRaw)
                .sync();
        long endTime = System.currentTimeMillis();
        log.info("请求KLSZ经济能力[响应], response: {}, 请求耗时: {}ms", response.getData(), (endTime - startTime));
        if (response.getSuccess()) {
            String data = response.getData();
            JSONObject obj = JSON.parseObject(data);
            return convertResultAndBilling(obj, endTime - reqStartTime);
        }
        throw new BusinessException(ExceptionEnum.OP_FAIL, "请求出错!");
    }


    @Data
    public static class KslzResDTO implements Serializable {
        private Head head;
        private String data;

        @Data
        public static class Head implements Serializable {
            public String requestId;
            public String uuid;
            public Integer code;
            public String msg;
        }

        public boolean isSuccess() {
            return 200 == getHead().getCode();
        }
    }
}
